<template>
  <!--列表-->
  <section>
    <el-form :inline="true" :model="employeeQuery" class="toolbar"
             style="text-align: left;margin-top: 20px">
      <el-form-item label="关键字">
        <el-input v-model="employeeQuery.keyword" placeholder="请输入部门名称进行查询"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch" >查询</el-button>
        <el-button type="success" @click="addDepartment">新增</el-button>
        <el-button type="success" @click="importExcel">导入</el-button>
        <el-button type="success" @click="exportExcel">按需导出</el-button>
        <el-link type="warning" href="http://8.134.177.48:8080/employee/exportExcel" target="_blank" style="margin-left: 20px">导出全部</el-link>
      </el-form-item>

    </el-form>
    <el-table :data="listDatas" highlight-current-row row-key="id" v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;" element-loading-text="拼命加载中">
      <el-table-column type="selection" width="55" :reserve-selection="true">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="员工姓名" width="120">
      </el-table-column>
      <el-table-column prop="password" label="密码" width="120">
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="120" sortable>
      </el-table-column>
      <el-table-column prop="email" label="邮箱">
      </el-table-column>
      <el-table-column prop='headImage' label="头像" width="180">
      </el-table-column>
      <el-table-column prop="department.name" label="所属部门">
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-popconfirm
          confirmButtonText='忍心抛弃'
          cancelButtonText='再给一次机会'
          icon="el-icon-info"
          iconColor="red"
          title="你确定要离我而去？"
          @confirm="batchRemove"
      >
        <el-button type="danger" slot="reference" :disabled="this.sels.length===0">批量删除</el-button>
      </el-popconfirm>
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     :page-sizes="sizes"
                     @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :current-page="currentPage"
                     :page-size="pageSize" :total="totalCount" style="float:right;">
      </el-pagination>
    </el-col>
    <!--  新增和编辑
          :visible.sync ture就打开  false就隐藏
    -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="employeeForm" :rules="employeeForm" ref="employeeForm">
        <el-form-item label="员工姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="employeeForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="name">
          <el-input v-model="employeeForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input type="email" v-model="employeeForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像" :label-width="formLabelWidth">
          <el-input type="text" v-model="employeeForm.headImage"></el-input>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth">
          <el-input type="number" min="0" max="120" v-model="employeeForm.age"></el-input>
        </el-form-item>
<!--        <el-form-item label="所属部门" :label-width="formLabelWidth">-->
<!--          <el-input type="number" v-model="employeeForm.department"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="部门经理" :label-width="formLabelWidth">-->
<!--          <el-select v-model="departmentForm.departments" value-key="id" clearable filterable >-->
<!--            <el-option v-for="(item,i) in managers" :label="item.username" :key="item.id" :value="item"/>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <!--
          options:级联框数据源
          props:
            expandTrigger:打开下级的方式
            value:配置对象的里面的提交数据的key
            label:配置对象的里面的显示数据的key
            checkStrictly:可选择任意的一级
        -->
        <el-form-item label="所属部门" :label-width="formLabelWidth">
          <el-cascader
              v-model="employeeForm.parent"
              :options="deptTrees"
              :props="{ expandTrigger: 'hover',
              value: 'id',
              label: 'name',
               checkStrictly:true
               }"
              ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="addLoading">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="dialogExportExcel" style="text-align: center">
<!--      <el-upload-->
<!--          class="upload-demo"-->
<!--          drag-->
<!--          action="http://localhost:8080/employee/importExcel"-->
<!--          multiple>-->
<!--        <i class="el-icon-upload"></i>-->
<!--        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>-->
<!--        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>-->
<!--      </el-upload>-->
      <el-upload
          class="upload-demo"
          ref="upload"
          action="http://localhost:8080/employee/importExcel"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :file-list="fileList"
          :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">不超过500kb</div>
      </el-upload>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="dialogProgress" style="text-align: center">
      <el-progress type="circle" :percentage="num" :status="success"></el-progress>
    </el-dialog>

  </section>

</template>

<script>

export default {
  data() {
    return {
      success:"",
      num:null,
      addLoading: false,
      listDatas: [],
      listLoading: true,//开启加载效果
      sels: [],//用户多选，选中的数据
      sizes: [5, 10, 20, 50],
      currentPage: 1,
      pageSize: 5,
      totalCount: 0,
      fileList: [],
      employeeQuery: {
        keyword: '',
      },
      formLabelWidth: '120px',
      title: "新增",
      employeeForm: {
        id: null,
        username: '',
        email: '',
        headImage:"",
        age: '',
        department_id: '',
      },
      dialogProgress:false,
      dialogFormVisible: false,
      dialogExportExcel:false,
      departmentRules: {
        username: [
          {required: true, message: '请输入员工姓名', trigger: 'blur'}
        ],
        email:[
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ]
      },
      managers: [],//装部门经理
      deptTrees: [],//装上级部门
    }
  },
  methods: {
    submitUpload() {
      this.$refs.upload.submit();
      let s = setInterval(res=>{
        this.loadListData();
        clearInterval(s)
      },1000)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    //批量删除
    batchRemove() {
      //把对象数组转成 id数组
      let deptIds = this.sels.map(function (obj,index,array){
        return obj.id;
      })
      this.$http.delete("/employee/deleteList",{data:deptIds}).then(res=>{
        let{msg,success} = res.data
        if (success){
          //操作成功   给一条提示
          this.$message.success("删除成功");
        }else {
          //操作失败  给一条失败的提示
          this.$message.error("操作失败")
        }
        this.loadListData();
      })
    },
    exportExcel(){
      console.log(this.sels)
      if (this.sels.length != 0){
        this.title="正在下载..."
        this.dialogProgress = true;
        this.num = 0;
        this.$http.put("/employee/exportMore",this.sels,{responseType:'blob'}).then(res=>{
          // window.open("http://localhost:8080/employee/exportMore")
          this.num = 30;
          let resBlob=new Blob([res.data],{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
          let a=document.createElement("a");
          let url=URL.createObjectURL(resBlob);
          this.num = 50;
          //将url赋值给a标签的href属性
          a.href=url;
          //下载的文件的文件名
          a.download="员工数据表.xlsx";
          this.num = 70;
          //触发click事件执行下载
          a.click();
          //要记得回收URL
          URL.revokeObjectURL(url);
          this.num = 100;
          this.success = "success";
          this.title = "下载完成!"
        })
      }else {
        this.$message.error("没有选择数据")
      }

    },
    importExcel(){
      this.title = "上传文件";
      this.dialogExportExcel = true;
    },
    loadListData() {
      //2、组装分页数据
      let param = {
        keyword: this.employeeQuery.keyword,
        currentPage: this.currentPage,
        pageSize: this.pageSize
      }
      this.$http.post("/employee", param).then(res => {
        let {data, success, msg} = res.data;
        if (success) {
          this.listDatas = data.dataList;
          this.totalCount = data.totals;
          console.log(this.listDatas)
          //关闭加载效果
          this.listLoading = false;
        }else{
          this.$message.error(msg)
        }
      })
    },
    loadManager() {
      this.$http.get("/employee/manager").then(res => {
        let {data, success, msg} = res.data;
        this.managers = data;
      })
    },
    //性别显示转换
    formatState: function (row, column) {
      return row.state === 1 ? '启用' : row.sex === 0 ? '禁用' : '未知';
    },
    selsChange: function (sels) {
      this.sels = sels;
      console.log(this.sels)
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/employee/"+row.id).then(res => {
          this.listLoading = false;
          if (res.data.success){
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }
          if(this.totalCount / this.pageSize)
          this.loadListData();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      // this.$refs.departmentForm.clearValidate();
      //1、获取当前行的数据
      //2、数据回显
      //3、打开弹出框
      this.title = '修改';
      this.employeeForm = row;
      console.log(this.employeeForm.parent)
      this.employeeForm.parent = row.department.id;
      if (this.employeeForm.headImage == null) {
        this.employeeForm.headImage="";
      }
      console.log(this.employeeForm.parent)
      this.dialogFormVisible = true;
    },
    //显示新增界面
    addDepartment: function () {
      //1、清空表单数据
      this.employeeForm = {
        id: null,
        username: '',
        email: '',
        headImage: '',
        age: '',
        department_id: '',
      }
      this.title = '新增';
      //2、打开弹出框
      this.dialogFormVisible = true;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPage = 1;
      this.loadListData();
    },
    handleCurrentChange(val) {
      //val 就是当前页的页码
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.loadListData();
    },
    onSearch() {
      this.listLoading = true;
      this.loadListData();
    },
    onSubmit() {
      this.$refs.employeeForm.validate((valid) => {
        if (valid) {
          this.addLoading = true;
          this.$confirm('确认提交吗？', '提示', {}).then(() => {

            if (this.employeeForm.parent){
              if (this.employeeForm.parent instanceof Array){
                this.employeeForm.department_id = this.employeeForm.parent[this.employeeForm.parent.length-1];
              }else {
                this.employeeForm.department_id = this.employeeForm.parent;
              }
            }
            //无论如何都要把this.departmentForm.parent置为空
            this.employeeForm.parent = null;
            console.log(this.employeeForm)
            this.$http.put('/employee', this.employeeForm).then(res => {
              this.addLoading = false;
              if (res.data.success) {
                this.$message.success("添加操作成功！");
              }else {
                this.$message.error("添加操作失败！");
              }
              this.dialogFormVisible=false;
              this.loadListData();
            });
          }).catch(() => {
            this.addLoading = false;
            this.$message.info("取消操作");
          })
        }
      });
    },
    loadDeptTree() {
      this.$http.get('/department/deptTree').then(res=>{
        this.deptTrees = res.data.data;
        console.log("--========")
        console.log(this.deptTrees)
      })
    },
  },
  mounted() {
    //加载完毕以后调用获取列表数据的方法
    this.loadListData();
    this.loadManager();
    this.loadDeptTree();

  }
}
</script>

<style scoped>

</style>